import { formatTime } from '@/tools/index'
import type { List } from '@/types/global.d'
import ExcelJS from 'exceljs'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

interface ColumnStyleConfig {
  width: number;
  alignment?: Partial<ExcelJS.Alignment>;
  font?: Partial<ExcelJS.Font>;
}

interface ColumnStyle {
  [key: string]: ColumnStyleConfig;
}
export function exportExcel(list: List[]) {
  const excelData = formatData(list)
  const fileName = `工作日志${dayjs().format('YYYY-MM-DD_HH-mm-ss')}`
  const columnStyle = {
    日期: {
      width: 20,
      alignment: {
        vertical: 'middle',
        horizontal: 'left',
        wrapText: true
      },
      font: {
        color: { argb: 'FFFF0000' },
        size: 14,
        bold: true
      }
    },
    内容: {
      width: 50,
      alignment: {
        vertical: 'top',
        horizontal: 'left',
        wrapText: true
      },
      font: {
        color: { argb: 'FF000000' },
        size: 12,
        bold: false
      }
    }
  }
  const columnOrder = ['日期', '内容']
  createExcel(excelData, fileName, columnOrder, columnStyle)
}
export async function createExcel(list: Object[], fileName: string, columnOrder: string[], columnStyle: ColumnStyle) {
  if (!list.length) {
    return ElMessage.info('无数据')
  }
  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet('sheet1')

  worksheet.columns = columnOrder.map((item) => ({
    header: item, key: item, width: columnStyle[item]?.width || 15
  }))

  // 添加数据
  worksheet.addRows(list)

  // 设置内容列样式：自动换行
  worksheet.eachRow((row, rowNumber) => {
    if (rowNumber > 1) { // 跳过标题行
      row.eachCell((cell, colNum) => {
        cell.alignment = columnStyle[columnOrder[colNum - 1]].alignment
        cell.font = columnStyle[columnOrder[colNum - 1]].font
      })
    }
  })

  // 在浏览器中保存文件
  const buffer = await workbook.xlsx.writeBuffer()

  // 创建Blob并下载
  const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  const url = URL.createObjectURL(blob)

  const link = document.createElement('a')
  link.href = url
  link.download = `${fileName}.xlsx`
  link.click()

  // 清理URL
  setTimeout(() => URL.revokeObjectURL(url), 5000)
}

export function formatData(list: List[]) {
  const res = list
    .filter((item) => !item.message.startsWith('Merge'))
    .sort((a, b) => a.date - b.date)
    .map((item) => {
      return { ...item, date: formatTime(item.date, 'YYYY-MM-DD') }
    })

  const result: { [key: string]: string[] } = {}
  res.forEach((item) => {
    const { date, message } = item
    const text = message.includes(':') ? message.split(':')[1].trim() : message.trim()
    if (!result[date]) {
      result[date] = [`1.${text}`]
    } else {
      result[date].push(`${result[date].length + 1}.${text}`)
    }
  })

  // 构建带样式的数据
  const excelData = Object.keys(result).map((date) => {
    return {
      日期: date,
      内容: result[date].join('\r\n')
    }
  })
  return excelData
}

// 前端筛选
export interface SearchParams<T> {
  currentPage: number;
  pageSize: number;
  prop: keyof T; // 排序字段，必须是 T 的键
  order: 'ascending' | 'descending';
}

// 过滤条件：包含 SearchParams，以及 T 上的任意字段作为过滤条件
export type Filter<T> = SearchParams<T> & Partial<Record<keyof T, any>>;
export default function search<T>(list: T[], filter: Filter<T>, fuzzyMatch: string[] = []) {
  const { currentPage, pageSize, prop, order } = filter
  const defaultCondition = { currentPage, pageSize, prop, order }
  const validKeys = (Object.keys(filter) as Array<keyof List>)
    .filter((item) => !Object.hasOwn(defaultCondition, item))
    .filter((item) => {
      const val = (filter as any)[item] // 类型稍复杂，先 any，下面优化
      if (Array.isArray(val)) {
        return val.length
      } else {
        return ![null, undefined, ''].some(sub => sub === val)
      }
    })
  // 过滤符合条件的项
  let allPage = list.filter((item) => {
    return validKeys.every((sub) => {
      const val = (item as any)[sub]
      const compare = (filter as any)[sub]
      if (fuzzyMatch.includes(sub)) {
        return (val as string).includes(compare as string)
      } else if (Array.isArray(compare)) {
        return compare[0] <= val && val <= compare[1]
      } else {
        return val === compare
      }
    })
  })
  // 排序
  if (prop && ['ascending', 'descending'].includes(order)) {
    allPage.sort((a, b) => {
      const aVal = a[prop]
      const bVal = b[prop]
      if (order === 'descending') {
        return bVal > aVal ? 1 : -1
      } else {
        return aVal > bVal ? 1 : -1
      }
    })
  }
  const total = [...allPage]
  // 分页
  if (currentPage && pageSize) {
    const start = (currentPage - 1) * pageSize
    const end = start + pageSize
    allPage = allPage.slice(start, end)
  }
  return [allPage, total]
}
